package com.qxzn.app.util;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtil {

    private static final int MIN_DELAY_TIME = 300;  // 两次点击间隔不能少于1000ms
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
            flag = false;
        }
        lastClickTime = currentClickTime;
        return flag;
    }

    public static void copyToClipboard(Context context, String text) {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData mClipData = ClipData.newPlainText(null, text);
        cm.setPrimaryClip(mClipData);
    }

    //手机号正则验证
    public static boolean isMobile(String str) {
        Pattern p = Pattern.compile("^((1[3-9]{1}[0-9]{1})+\\d{8})$"); // 验证手机号
        Matcher m = p.matcher(str);
        return m.matches();
    }

    public static String getSecurityPhoneString(String phone) {
        if (isMobile(phone))
            return new StringBuilder(phone).replace(3, 7, "****").toString();
        else
            return "***********";
    }

    public static void showKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            view.requestFocus();
            imm.showSoftInput(view, 0);
        }
    }

    public static void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 跳转到应用详情界面
     */
    public static void gotoAppDetailIntent(Context activity) {
        Intent intent = new Intent();
        intent.setAction(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + activity.getPackageName()));
        activity.startActivity(intent);
    }

    /**
     * 8-16位同时包含字母和数字验证
     *
     * @param str
     * @return
     */
    public static boolean isLettersAndNumbers(String str) {
        if (str == null) {
            return false;
        }
        Pattern pattern = Pattern.compile("^(?!([\\ \\\\\\[\\]!\"#$%&'()*+,-./:;<=>?@^_`{|}~]|[a-zA-Z])+$)(?![0-9]+$)([0-9a-zA-Z]+){8,16}$");
        return pattern.matcher(str).matches();
    }

    /**
     * @param str 需要判断的字符
     * @return 是汉字(true), 不是汉字(false)
     */
    public static boolean isChineseChar(String str) {
        return str.matches("[\u4e00-\u9fa5]+");
    }

}
